import { Router } from '@angular/router';
import { Injectable, Injector } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { MenuService, SettingsService, TitleService } from '@delon/theme';
import { ACLService } from '@delon/acl';
import { zip } from 'rxjs/observable/zip';
import { I18NService } from '../i18n/i18n.service';
import { TranslateService } from '@ngx-translate/core';

import { AppSessionService } from '@shared/common/session/app-session.service';
import { AppConsts } from '@shared/AppConsts';
import { Abp ,abp } from '@core/net/abp';

import * as moment from 'moment';
import * as _ from 'lodash';

/**
 * 用于应用启动时
 * 一般用来获取应用所需要的基础数据等
 */
@Injectable()
export class StartupService {
    constructor(
        private menuService: MenuService,
        private translate: TranslateService,
        private i18n: I18NService,
        private settingService: SettingsService,
        private aclService: ACLService,
        private titleService: TitleService,
        private httpClient: HttpClient,
        private injector: Injector) { }

        public static getCurrentClockProvider(currentProviderName: string): abp.timing.IClockProvider {
            if (currentProviderName === 'unspecifiedClockProvider') {
                return Abp.timing.unspecifiedClockProvider;
            }

            if (currentProviderName === 'utcClockProvider') {
                return Abp.timing.utcClockProvider;
            }

            return Abp.timing.localClockProvider;
        }
    
    checkMenuPerssion(menus){
        _.forEach(menus,(item)=>{
            
            item.hide = item.permission && !Abp.auth.isGranted(item.permission);
            
            if(item.children!= undefined && item.children.length >0){
                this.checkMenuPerssion(item.children);
            }
        });
    }

    load(callback: () => void): Promise<any> {
        // only works with promises
        // https://github.com/angular/angular/issues/15088




        return new Promise((resolve, reject) => {
            zip(
                this.httpClient.get(`assets/i18n/zh-CN.json`),
                this.httpClient.get('assets/app-data.json')
            ).subscribe(([langData, appData]) => {
                // setting language data
                this.translate.setTranslation('zh-CN', langData);
                this.translate.setDefaultLang('zh-CN');

                // application data
                const res: any = appData;
                // 应用信息：包括站点名、描述、年份
                this.settingService.setApp(res.app);
                // 用户信息：包括姓名、头像、邮箱地址
                this.settingService.setUser(res.user);
                // ACL：设置权限为全量
                this.aclService.setFull(true);
               
                // 设置页面标题的后缀
                this.titleService.suffix = res.app.name;

                AppConsts.remoteServiceBaseUrl = res.url.remoteServiceBaseUrl;
                AppConsts.appBaseUrl = res.url.appBaseUrl;


                const cookieLangValue = Abp.utils.getCookieValue('Abp.Localization.CultureName');
                const token = Abp.auth.getToken();

                const requestHeaders = {
                    //'.AspNetCore.Culture': ('c=' + cookieLangValue + '|uic=' + cookieLangValue),
                    //'Abp.TenantId': Abp.multiTenancy.getTenantIdCookie()
                };

                if(Abp.multiTenancy.getTenantIdCookie()){
                    requestHeaders['Abp.TenantId']=Abp.multiTenancy.getTenantIdCookie().toString();
                }

                if (token) {
                    requestHeaders['Authorization'] = 'Bearer ' + token;
                }

                this.httpClient.get(AppConsts.remoteServiceBaseUrl + '/AbpUserConfiguration/GetAll',{
                    headers:requestHeaders
                })
                    .subscribe(allres => {
                        const all: any = allres;
                        const allSetting = all.result;

                        Abp.log.debug({
                            all: allSetting
                        });

                        Abp.multiTenancy.setGlobal(allSetting.multiTenancy);
                        Abp.session.setGlobal(allSetting.session);
                        Abp.localization.setGlobal(allSetting.localization);
                        Abp.features.setGlobal(allSetting.features);
                        Abp.auth.setGlobal(allSetting.auth);
                        Abp.nav.setGlobal(allSetting.nav);
                        Abp.setting.setGlobal(allSetting.setting);

                        Abp.clock.setGloabl(allSetting.clock);
                        Abp.timing.setGloabl(allSetting.timing);


                        Abp.clock.provider = StartupService.getCurrentClockProvider(allSetting.clock.provider);

                        moment.locale(Abp.localization.currentLanguage.name);

                        (window as any).moment.locale(Abp.localization.currentLanguage.name);

                        if (Abp.clock.provider.supportsMultipleTimezone) {
                            moment.tz.setDefault(Abp.timing.timeZoneInfo.iana.timeZoneId);
                             (window as any).moment.tz.setDefault(Abp.timing.timeZoneInfo.iana.timeZoneId);
                        }
                        AppConsts.recaptchaSiteKey = Abp.setting.get('Recaptcha.SiteKey');
                        AppConsts.subscriptionExpireNootifyDayCount = parseInt(Abp.setting.get('App.TenantManagement.SubscriptionExpireNotifyDayCount'),null);

                        const appSession = this.injector.get(AppSessionService);

                        
                        this.checkMenuPerssion(res.menu);
                        console.log(res.menu);

                         // 初始化菜单
                        this.menuService.add(res.menu);

                        appSession.init().then(() => {
                            resolve(res);
                        });

                    });

            }, (err: HttpErrorResponse) => {
                resolve(null);
            });
        });
    }
}
